import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import Users from '../components/user/User'
import Rights from '../components/right/Right'
import Roles from '../components/right/Roles'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' }, // 重定向
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫，用于校验访问的路径是否有token（是否登录）
// to:将要访问的路径  from:从哪个路径访问过来的 next:是个函数，表示放行
// 调用方式 1.next():直接放行 2.next('/login'):强制跳转
router.beforeEach((to, from, next) => {
  // 1.直接放行/login
  if (to.path === '/login') return next()
  // 2.其他路径的跳转要先获取token
  const tokenStr = window.sessionStorage.getItem('token')
  // 无token，跳转到/login
  if (!tokenStr) return next('/login')
  // 有token则直接放行
  next()
})

export default router
